package ui.tab;

import entity.Table;
import ui.AgCodeMain;
import utils.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.*;
import java.util.List;

/**
 * 数据库信息页面
 * Created by liushun on 2016/11/21.
 */
public class DataBaseInfoTab extends JPanel {

    private final Object[] columnNames = {"表名称", "表描述", "记录数"};

    private JTable table;

    public DataBaseInfoTab(){
        table = new JTable(new DefaultTableModel(columnNames, 0));
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalTextPosition(SwingConstants.LEFT);
        renderer.setForeground(Color.blue);
        table.getTableHeader().setDefaultRenderer(renderer);
        JScrollPane scrollPane = new JScrollPane(table);
        scrollPane.setBounds(0, 0 ,388, 280);
        JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
        verticalScrollBar.setPreferredSize(new Dimension(12, 0));
        this.add(scrollPane);
        this.setLayout(null);
    }

    public void setTableList(final String sjk_txt){
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                List<Table> tableList = null;
                try {
                    tableList = DBUtil.queryTableList(sjk_txt);
                } catch (Exception e) {
                    AgCodeMain.log("数据库没有建立可以用的连接!", Color.red, true);
                    e.printStackTrace();
                    JOptionPane.showMessageDialog(null, "数据库连接失败!", "提示", JOptionPane.ERROR_MESSAGE);
                }
                Object[][] rowData = new Object[tableList.size()][columnNames.length];

                if (tableList != null && !tableList.isEmpty()) {
                    int j = 0;
                    for (int i = 0; i < tableList.size(); i++) {
                        Table t = tableList.get(i);
                        rowData[j][0] = t.getTableName();
                        rowData[j][1] = t.getTableDescription();
                        rowData[j][2] = t.getTableLines();
                        j++;
                    }
                }
                table.setModel(new DefaultTableModel(rowData, columnNames));
                table.getColumnModel().getColumn(0).setPreferredWidth(130);
                table.getColumnModel().getColumn(1).setPreferredWidth(170);
                table.getColumnModel().getColumn(2).setPreferredWidth(65);
                table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
                table.revalidate();
            }
        });
    }
}
